import router from '@/router'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import store from '@/store'
import { asyncRoutes } from '@/router'
// 白名单
const whiteList = ['/login', '/404']
// 前置守卫
router.beforeEach(async(to, from, next) => {
  // 前置守卫在路由跳转之前发生的回调
  NProgress.start()
  if (store.getters.token) {
    // 存在token
    if (to.path === '/login') {
      next('/')
      NProgress.done()
    } else {
      // 放过
      // 判断是否获取过资料
      if (!store.getters.userId) {
        const { roles } = await store.dispatch('user/getUserInfo')
        console.log(roles.menus)
        const filterRoutes = asyncRoutes.filter(item => {
          // return true或false
          return roles.menus.includes(item.name)
        })
        store.commit('user/setRouter', filterRoutes)
        router.addRoutes([...filterRoutes, { path: '*', redirect: '/404', hidden: true }])
        next(to.path)
      } else {
        next()
      }
    }
  } else {
    //
    if (whiteList.indexOf(to.path) > -1) {
      next()
    } else {
      next('/login') // 跳转到登录页
      NProgress.done()
    }
  }
})
// 后置守卫
router.afterEach(() => {
  NProgress.done()
})
